var _gl = require('opengl');
var _geometry = require('core/glm.js');
var _glm = _geometry.glm;
var _matrix4 = _geometry.matrix4;
var _createStructor = require('glcore/meshbuffer.js').createStructor;
var _createMesh = require('glcore/meshbuffer.js').createMesh;
var _Buffer = require('glcore/buffer.js').Buffer;
var _Filler = require('drawable/framefiller.js');

function Grid(frame) {
    this.mFrame = frame;
    this.mWidth = frame.width();
    this.mHeight = frame.height();

    this.mMatrix = new _matrix4();
    this.mPoint = new (_createStructor('p3t2'))();
    this.mFiller = _Filler.createFiller(this.mPoint, frame);

    this.mDark = this.createBuffer(6);
    this.mLight = this.createBuffer(6);
    this.mAll = this.createBuffer(6);
    this.mMeshes = [this.mDark, this.mLight, this.mAll];

    this.initElement();
}
Grid.prototype.initElement = function () {
    var w = this.mWidth / 2;
    var h = this.mHeight;

    this.mMatrix.identity();
    this.mFiller.setBuffer(this.mDark);
    this.mFiller.setMatrix(this.mMatrix);
    this.mFiller.seek(0);
    this.mFiller.appendRect(0, 0, w, h);

    this.mMatrix.identity();
    this.mMatrix.translate(-w, 0);
    this.mFiller.setBuffer(this.mLight);
    this.mFiller.setMatrix(this.mMatrix);
    this.mFiller.seek(0);
    this.mFiller.appendRect(w, 0, w * 2, h);

    this.mMatrix.identity();
    this.mFiller.setBuffer(this.mAll);
    this.mFiller.setMatrix(this.mMatrix);
    this.mFiller.seek(0);
    this.mFiller.appendRect(0, 0, w * 2, h);
};
Grid.prototype.createBuffer = function (points) {
    return new _Buffer({
        stride: this.mPoint.byteLength,
        count: points,
        type: Int8Array,
        normalize: false
    });
};
Grid.prototype.createGLBuffer = function (points) {
    return _createMesh('p3t2', points, _gl.TRIANGLES);
};
/**
 * @param offset
 * @param id 0,1,2
 */
Grid.prototype.appendCell = function (offset, id, buffer, index) {
    _glm.translation(this.mMatrix, offset);
    this.mFiller.transform(this.mMatrix, this.mMeshes[id], 0, buffer, index, 6);
    return index + 6;
};

module.exports = Grid;